package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.Friend;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.vo.ContactVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @auther : 白月尘
 * @date : 18:15  2021/10/23
 */
@Service
public class MessagesService {
    @DubboReference
    private FriendApi friendApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @DubboReference
    private UserInfoApi userInfoApi;

    public void contacts(Long id) {
        friendApi.save(id, UserHolder.getUserId());
        huanXinTemplate.addContact("hx" + UserHolder.getUserId(), "hx" + id);
    }

    public PageResult findFriends(Integer page, Integer pageSize) {
        List<Friend> list = friendApi.findFriends(page, pageSize, UserHolder.getUserId());
        if (list == null || list.size() <= 0) {
            return new PageResult();
        }
        List<Long> friendId = CollUtil.getFieldValues(list, "friendId", long.class);
        Map<Long, UserInfo> map = userInfoApi.findAll(friendId);
        List<ContactVo> vos = new ArrayList<>();
        for (Friend friend : list) {
            UserInfo userInfo = map.get(friend.getFriendId());
            ContactVo init = ContactVo.init(userInfo);
            vos.add(init);
        }
        return new PageResult(page, pageSize, 0l, vos);
    }

    public UserInfoVo userInfo(String huanXinId) {
        String hx = huanXinId.replace("HX", "");
        Long value = Long.valueOf(hx);
        System.out.println(value);
        System.out.println(value+""+value.getClass());
        UserInfo userInfo = userInfoApi.findById(value);
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, vo);
        if (userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }
        return vo;
    }
}
